package interviewClassic150;

import java.util.HashMap;
import java.util.Map;

public class WordPattern {
    public boolean wordPattern(String pattern, String s) {
        //定义两个map来映射pattern中每个字母对应的字符串
        String[] map = new String[26];
        Map<String,Character> sToPattern = new HashMap<>();
        int n = pattern.length();
        String[] strArr = s.split(" ");
        if (n != strArr.length) return false;

        for (int i = 0; i < n; i++) {
            char curChar = pattern.charAt(i);
            int index = curChar - 'a';
            String curStr = strArr[i];
            if (map[index] == null) map[index] = curStr;
            else {
                String mapStr = map[index];
                if (!mapStr.equals(curStr)) return false;
            }

            if (!sToPattern.containsKey(curStr)) sToPattern.put(curStr,curChar);
            else {
                char mapChar = sToPattern.get(curStr);
                if (mapChar != curChar) return false;
            }
        }

        return true;
    }
}
